import axios from 'axios';
import _g from '@/assets/js/global.js';
import {Toast} from 'vant';

let loading;
let needLoadingRequestCount = 0 // 声明一个对象用于存储请求个数

function startLoading() {
  loading = Toast.loading({
    duration: 0, // 持续展示 toast
    message: '加载中...',
    forbidClick: true,
    overlay: true,
    loadingType: 'spinner',
  })
}

function endLoading() {
  setTimeout(() => {
    loading.clear();
  }, 1000)
}

function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

function hideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

axios.defaults.baseURL = 'http://120.24.218.54:8080';
axios.defaults.timeout = 7000;
axios.defaults.withCredentials = true;
axios.defaults.headers = {
  // 'Content-type': 'application/json;charset=utf-8'
};

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  if (config.headers.isShowFullLoading === "F") {
    //do nothing
  } else {
    showFullScreenLoading();
  }
  return config;
}, error => {
  // 对请求错误做些什么
  hideFullScreenLoading();
  _g.showMsg("danger", "发送请求失败");
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(response => {
  // 对响应数据做点什么
  hideFullScreenLoading();
  if (response.data.msg === '请先登录') {
    _g.reLogin();
    return;
  }
  if (response.status === 200) {
    //响应成功
    return response.data;
  }
}, error => {
  console.log(error.msg);
  hideFullScreenLoading();
  // _g.showMsg('danger', `请刷新重试`);
});

export default axios;

